<template>
  <div class="addOrEditSpareBox">
    <breadcrumb
      :titleArr="titleArr"
      @back="breadcrumbBack"
      class="bread-crumb"
    ></breadcrumb>
    <el-tabs v-model="firstName">
      <el-tab-pane label="备件信息" name="spareInfo">
        <el-form :model="accessForm" :rules="ruleSpareParts" ref="accessForm">
          <el-form-item label="备件编号" prop="spareNumber">
            <el-input
              v-model="accessForm.spareNumber"
              placeholder="请输入"
              clearable
              maxlength="50"
            ></el-input>
          </el-form-item>
          <el-form-item label="备件名称" prop="name">
            <el-input
              v-model="accessForm.name"
              placeholder="请输入"
              clearable
              maxlength="20"
            ></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="typeId">
            <el-cascader
              style="width:100%"
              v-model="accessForm.typeId"
              :options="spareTypeOptions"
              :props="{
                checkStrictly: true,
                multiple: false,
                children: 'children',
                emitPath: true,
                label: 'typeName',
                value: 'id',
                expandTrigger: 'hover'
              }"
              clearable
              filterable
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="型号" prop="model">
            <el-input v-model="accessForm.model" placeholder="请输入" clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="单位" prop="unitId">
            <m7Select
              filterable
              v-model="accessForm.unitId"
              size="mini"
              :options="unitTypeOptions"
              :defaultProps="{ value: 'id', label: 'typeName' }"
              placeholder="请选择"
            >
            </m7Select>
          </el-form-item>
          <el-form-item label="销售价" prop="price">
            <el-input-number
              v-model="accessForm.price"
              placeholder="请输入"
              :controls="false"
              :precision="2"
              :min="0"
              :max="100000000"
            >
            </el-input-number>
          </el-form-item>
          <el-form-item label="备注描述" prop="description" class="remarks">
            <el-input
              type="textarea"
              :rows="4"
              v-model="accessForm.description"
              placeholder="请输入"
              size="mini"
              maxlength="200"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <el-form-item label="备件图片 (最多上传9张)" class="remarks">
            <el-upload
              :class="{ hide: overLimitNum }"
              accept=".jpg, .gif, .png, .jpeg, .bmp, .psd, .tif, .jfif"
              action=""
              list-type="picture-card"
              :file-list="fileList"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload"
              :http-request="uploadRequest"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus" /><br /><span class="upload-word"
                >上传图片</span
              >
            </el-upload>
          </el-form-item>
          <el-dialog :visible.sync="imgShow" :modal="false" width="60%">
            <img :src="previewImgUrl" alt="" width="100%" height="auto" />
          </el-dialog>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div class="more-btn">
      <el-button class="cancel" size="mini" @click="cancelFun">取消</el-button>
      <el-button size="mini" type="primary" @click="saveFun">提交</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import { uploadQiniu } from '@/utils/upload'
import { commonAction } from '@/utils/common'
import breadcrumb from '@/components/breadcrumb/breadcrumb.vue'
import { Form as ElForm } from 'element-ui'
import { state, mutations } from '../store/spareData'
import { numberAndLetter } from '@/utils/validate'
interface AccessForm {
  spareNumber: string
  id: any
  name: string
  typeId: any
  model: string
  description: string
  unitId: any,
  price: any,
  attach: any
}
@Component({
  name: 'addOrEditOrDetailSpare',
  components: { breadcrumb }
})
export default class SparePartsAddOrEdit extends Vue {
  @Prop() private showStatus!: string
  @Prop({ default: [] }) private titleArr!: any
  private $message: any

  private firstName: string = 'spareInfo'

  private fileName = '' // 本地文件名称

  public accessForm: AccessForm = { // 备件信息
    spareNumber: '',
    id: '',
    name: '',
    typeId: '',
    model: '',
    unitId: '',
    price: undefined,
    description: '',
    attach: []
  }

  public fileList: any = [] // 备件图片

  private previewImgUrl: string = '' // 预览图片的地址

  private imgShow: boolean = false // 是否展示预览的图片

  private overLimitNum: boolean = false // 判断上传图片数量是否大于上传的图片数量，若大于隐藏上传按钮

  private validateModelPrefix = (rule, value, callback) => {
    if (!value || !numberAndLetter(value)) {
      callback(new Error('请输入正确的备件编号，只能是字母或数字'))
    } else {
      callback()
    }
  }

  private ruleSpareParts: object = { // 备件信息的校验
    spareNumber: [{ required: true, message: '请输入正确的备件编号，只能是字母或数字', validator: this.validateModelPrefix, trigger: 'blur' }],
    name: [{ required: true, message: '请输入备件名称', trigger: 'blur' }],
    typeId: [{ required: true, message: '请选择类型', trigger: 'change' }],
    model: [{ required: true, message: '请输入型号', trigger: 'blur' }],
    unitId: [{ required: true, message: '请选择单位', trigger: 'change' }],
    price: [{ required: true, message: '请输入销售价', trigger: 'blur' }]
  }

  get spareTypeOptions () {
    return state.spareTypeList
  }

  get unitTypeOptions () {
    return state.unitList
  }

  @Watch('accessForm.attach', { immediate: true, deep: true }) // 监听图片数量是否超出限制
  private accessFormChange (newValue: any, oldValue: any) {
    if (newValue && newValue.length >= 9) {
      this.overLimitNum = true
    } else {
      this.overLimitNum = false
    }
  }

  private uploadRequest (request: any) { // 七牛上传
    uploadQiniu({ type: 'common', fileName: this.fileName }, request)
  }

  private uploadSuccess (data: any) { // 上传成功
    const url = data.key ? `${data.domain}/${data.key}` : ''
    this.accessForm.attach.push({
      name: this.fileName,
      url
    })
  }

  private uploadError () { // 上传失败
    this.$message({ message: '文件上传失败，请重新选择文件上传', type: 'error' })
  }

  private beforeUpload (file: any) { // 上传前验证文件合法性
    if (this.accessForm.attach.length > 9) {
      this.$message({ message: '最多只允许上传10张图片', type: 'error' })
      return false
    }
    this.fileName = file.name.replace(/\s/g, '')
    if (file.size / 1024 / 1024 > 20) {
      this.$message({ message: '图片大小不能超过20M', type: 'error' })
      return false
    }
  }

  private handlePictureCardPreview (file: any) { // 图片预览
    if (file.response) {
      this.previewImgUrl = file.response.key ? `${file.response.domain}/${file.response.key}` : ''
    } else {
      this.previewImgUrl = file.url
    }
    this.imgShow = true
  }

  private handleRemove (file: any) { // 移除图片
    let delImgUrl = ''
    if (file.response) { // 新增删除
      delImgUrl = file.response.key ? `${file.response.domain}/${file.response.key}` : ''
    } else { // 编辑删除
      delImgUrl = file.url ? file.url : ''
    }
    this.accessForm.attach.forEach((ele, index) => {
      if (ele.url === delImgUrl) {
        this.accessForm.attach.splice(index, 1)
      }
    });
  }

  private saveFun () {
    const formRef = this.$refs.accessForm as ElForm
    const { spareNumber, id, name, typeId, model, unitId, price, description, attach } = this.accessForm
    let typeIdStr = typeId
    if (Array.isArray(typeId)) {
      typeIdStr = typeId.join()
    }
    const sendData = {
      spareNumber,
      name,
      typeId: typeIdStr,
      model,
      unitId,
      price,
      description,
      attach
    }
    formRef.validate(valide => {
      if (valide) {
        if (this.showStatus === 'edit') { // 编辑
          commonAction({
            url: '/server-work/action/spare/update',
            method: 'post',
            data: { id, ...sendData }
          }).then(res => {
            if (res.success) {
              this.$message.success('编辑成功')
              mutations.setRequestData('spare', false)
              this.$emit('handleSaveFun')
            }
          })
        } else { // 新增
          commonAction({
            url: '/server-work/action/spare/create',
            method: 'post',
            data: sendData
          }).then(res => {
            if (res.success) {
              this.$message.success('创建成功')
              mutations.setRequestData('spare', false)
              this.$emit('handleSaveFun')
            }
          })
        }
      }
    })
  }

  private cancelFun () {
    this.$emit('cancelFun')
  }

  private breadcrumbBack () {
    this.$emit('pageBack')
  }
}
</script>
<style lang="stylus" scoped>
.el-input-number
  width 100%
  >>> .el-input__inner
    text-align left
.addOrEditSpareBox
  border 1px solid $border-main
  border-radius 10px
  height calc(100vh - 86px)
  overflow auto
  box-shadow 0px 0px 4px 0px #e0e6f0,0px 1px 4px 0px #e0e6f0
  .el-tabs
    margin 12px 24px 60px
  .el-form
    display flex
    flex-wrap wrap
    .el-form-item
      width 40%
      margin-right 24px
    .remarks
      &.el-form-item
        width calc(80% + 24px)
      >>> .el-form-item__label
        width 100%
        text-align left
  .more-btn
    bottom -1px
    right 1px
    width 99%
    height 60px
    padding 0 16px
    line-height 48px
    text-align right
    position absolute
    background #fff
    z-index 20
      .cancel
        margin-right 10px
>>> .el-upload--picture-card
  width 80px
  height 80px
  border-radius 4px
  line-height 10px
  .el-icon-plus
    font-size 18px
    color #A6A6AE
    margin 18px 0 9px
  .upload-word
    font-size 12px
    font-family PingFang SC
    color #767E91
>>> .el-upload-list__item
  width 80px
  height 80px
  border-radius 4px
.hide
  >>> .el-upload--picture-card
    display none
</style>
